import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/singleton/amap_repository/amap_repository.dart';
import 'package:e_reception_flutter/singleton/location_repository/location_repository.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/company/choose_city/bean/choose_city_list_item_bean.dart';
import 'package:e_reception_flutter/ui/company/choose_city/choose_city_page.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_view_model.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_location_utils.dart';
import 'package:e_reception_flutter/vg_widgets/light_annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/vg_text_field.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_base/vg_widget_lib.dart';

class SmartHomeCreateOrEditAddressPage extends StatefulWidget {

  final String shid;
  final String gps;
  final String province;
  final String city;
  final String district;
  final String address;
  final String addressCode;
  final Function(String detailAddress, String gps) onSave;
  const SmartHomeCreateOrEditAddressPage({Key key,
    this.shid, this.gps, this.province, this.city,
    this.district, this.address, this.addressCode, this.onSave}) : super(key: key);

  static const String ROUTER = "SmartHomeCreateOrEditAddressPage";

  @override
  _SmartHomeCreateOrEditAddressPageState createState() => _SmartHomeCreateOrEditAddressPageState();

  static Future<Map<String, ChooseCityListItemBean>> navigatorPush(BuildContext context, String shid, String gps,
      String province, String city, String district, String address, String addressCode, Function(String detailAddress, String gps) onSave) {
    return RouterUtils.routeForFutureResult(
      context,
      SmartHomeCreateOrEditAddressPage(
        shid: shid,
        gps: gps,
        province: province,
        city: city,
        district: district,
        address: address,
          onSave: onSave,
      ),
      routeName: SmartHomeCreateOrEditAddressPage.ROUTER,
    );
  }
}

class _SmartHomeCreateOrEditAddressPageState extends BaseState<SmartHomeCreateOrEditAddressPage> {
  Map<String, ChooseCityListItemBean> _resultLocationMap;
  TextEditingController _editingAddressController;
  VgLocation _locationPlugin;
  String _province;
  String _city ;
  String _district;
  String _address;
  String _gps;
  String _addressCode;

  String _detailAddress;
  String _originDetailAddress;

  SmartHomeViewModel _viewModel;

  @override
  void initState() {
    super.initState();
    _viewModel = new SmartHomeViewModel(this);
    if(StringUtils.isNotEmpty(widget?.gps)){
      _gps = widget?.gps;
    }
    _address = widget?.address;
    _detailAddress = "${_getAddressStr()}${_address??""}";
    _originDetailAddress = _detailAddress;
    Future<String> latlng = VgLocationUtils.getCacheLatLngString();
    latlng.then((value){
      print("缓存gps:" + value);
      _gps = value;
    });
    _editingAddressController = TextEditingController(text: widget?.address)
      ..addListener(() => _notifyChange());
    if(StringUtils.isEmpty(widget?.gps??"")){
      _initLocation();
    }
  }

  _initLocation(){
    _locationPlugin = VgLocation();
    _locationPlugin.requestSingleLocationWithoutCheckPermission((locationMap) {
      print("能不能收到");
      var transResult = VgLocationUtils.transLocationToMap(locationMap);
      if (transResult == null) {
        _resultLocationMap = {
          CHOOSE_PROVINCE_KEY:
          ChooseCityListItemBean("110000", "北京市"),
          CHOOSE_CITY_KEY: ChooseCityListItemBean("110100", "北京市"),
          CHOOSE_DISTRICT_KEY:
          ChooseCityListItemBean("110101", "东城区", latitude: 39.917544, longitude: 116.418757)
        };
      }else{
        _resultLocationMap = transResult;
      }
      setState(() {
        _getAddressStr();
      });
    });
  }


  @override
  void dispose() {
    _editingAddressController?.dispose();
    if (_locationPlugin != null) _locationPlugin.dispose();
    super.dispose();
  }

  ///通知更新
  _notifyChange() {
    _address = _editingAddressController?.text?.trim();
    _detailAddress = "${_getAddressStr()}${_address??""}";
    setState(() { });
  }



  String _getAddressStr() {
    _province = widget?.province;
    _city = widget?.city;
    _district = widget?.district;
    _addressCode = widget?.addressCode;
    if (_resultLocationMap == null || _resultLocationMap.isEmpty) {
      // _initLocation();
      if (_province == _city) {
        return "$_province$_district";
      } else {
        return "$_province$_city$_district";
      }
    }else{
      if(StringUtils.isNotEmpty(_getGpsStr())){
        _gps = _getGpsStr();
      }
      _addressCode = _resultLocationMap[CHOOSE_DISTRICT_KEY]?.sid;
      _province = _resultLocationMap[CHOOSE_PROVINCE_KEY]?.sname;
      _city = _resultLocationMap[CHOOSE_CITY_KEY]?.sname;
      _district = _resultLocationMap[CHOOSE_DISTRICT_KEY]?.sname;
      if(StringUtils.isEmpty(_district)){
        _district = "";
      }
      if (_province == _city) {
        return "$_province$_district";
      } else {
        return "$_province$_city$_district";
      }
    }
  }

  String _getGpsStr() {
    double latitude = _resultLocationMap[CHOOSE_DISTRICT_KEY]?.latitude;
    double longitude = _resultLocationMap[CHOOSE_DISTRICT_KEY]?.longitude;
    return latitude.toString() + "," + longitude.toString();
  }

  @override
  Widget build(BuildContext context) {
    return LightAnnotatedRegion(
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        backgroundColor: Color(0xFFF6F7F9),
        body: Column(
          children: [
            _toTopBarWidget(),
            _toPCDWidget(),
            SizedBox(height: 1),
            _toDetailWidget(),
          ],
        ),
      ),
    );
  }

  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      title: "门店地址",
      isShowBack: true,
      backgroundColor: Color(0xFFF6F7F9),
      titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      rightWidget: _toSaveButtonWidget(),
    );
  }

  Widget _toSaveButtonWidget() {
    return CommonFixedHeightConfirmButtonWidget(
      isAlive: isCanSave(),
      width: 48,
      height: 24,
      unSelectBgColor:Color(0xFFCFD4DB),
      selectedBgColor:
      ThemeRepository.getInstance().getPrimaryColor_1890FF(),
      unSelectTextStyle: TextStyle(
          color: Colors.white,
          fontSize: 12,
          fontWeight: FontWeight.w600),
      selectedTextStyle: TextStyle(
          color: Colors.white, fontSize: 12, fontWeight: FontWeight.w600),
      text: "保存",
      onTap: (){
        _save();
      },
    );
  }

  bool isCanSave(){
    return _detailAddress != _originDetailAddress;
  }
  void _save(){
    if(!isCanSave()){
      return;
    }
    if(StringUtils.isNotEmpty(widget?.shid??"")){
      _viewModel.editAddressInfo(context, widget?.shid, _province, _city, _district,
          _address, _gps, _addressCode);
      return;
    }
    widget?.onSave?.call(_address, _gps);
    RouterUtils.pop(context, result: _resultLocationMap);
  }

  ///省市区
  Widget _toPCDWidget(){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        HudUtils.showLoading(context,true);
        LocationRepository.getInstance().init(callback: (success)async{
          HudUtils.showLoading(context,false);
          Map<String, ChooseCityListItemBean> result =
          await ChooseCityPage.navigatorPush(context,
              subLevel: 3, selected: _resultLocationMap, lightTheme: true);
          if (result == null || result.isEmpty) {
            return;
          }
          _resultLocationMap = result;
          _notifyChange();
        });
      },
      child: Container(
        height: 50,
        alignment: Alignment.center,
        color: Colors.white,
        child: Row(
          children: [
            SizedBox(width: 15,),
            Text(
              "所在区县",
              style: TextStyle(
                fontSize: 14,
                color: Color(0XFF5E687C),
              ),
            ),
            SizedBox(width: 15,),
            Text(
              StringUtils.isNotEmpty(_getAddressStr())?_getAddressStr():"请选择",
              style: TextStyle(
                fontSize: 14,
                color: StringUtils.isNotEmpty(_getAddressStr())?Color(0XFF21263C):Color(0XFFB0B3BF),
              ),
            ),
            Spacer(),
            Image.asset(
              "images/icon_arrow_right_grey.png",
              width: 6,
              color: Color(0XFF8B93A5),
            ),
            SizedBox(width: 15,),
          ],
        ),
      ),
    );
  }

  ///详细地址
  Widget _toDetailWidget(){
    return Container(
        height: 50,
        padding: EdgeInsets.symmetric(horizontal: 15),
        color: Colors.white,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              "详细地址",
              style: TextStyle(
                fontSize: 14,
                color: Color(0XFF5E687C),
              ),
            ),
            SizedBox(width: 15,),
            Expanded(
                flex: 1,
                child: VgTextField(
                  controller: _editingAddressController,
                  keyboardType: TextInputType.text,
                  style: TextStyle(
                      color: Color(0XFF21263C),
                      fontSize: 14),
                  maxLimitLength: 30,
                  decoration: new InputDecoration(
                      counterText: "",
                      hintText: "请输入",
                      border: InputBorder.none,
                      hintStyle: TextStyle(
                          fontSize: 14,
                          color: Color(0XFFB0B3BF))),
                )),
          ],
        ));
  }

}

